package online.shiming.file.util;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import cn.hutool.core.util.IdUtil;

/**
 * @author ShiMing
 * @version 1.0
 * @name FileUtils
 * @description TODO
 * @date 2020/11/21
 */

public class FileUtils {
    public static File castToFile(MultipartFile multipartFile) throws IOException {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名，防止生成的临时文件重复
        final File excelFile = File.createTempFile(IdUtil.simpleUUID(), prefix);

        multipartFile.transferTo(excelFile);
        return excelFile;
    }

    public static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.deleteOnExit();
            }
        }
    }
}
